package com.zzq.guli.service.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzq.guli.service.base.except.GuliException;
import com.zzq.guli.service.base.helper.JwtHelper;
import com.zzq.guli.service.base.helper.JwtInfo;
import com.zzq.guli.service.base.result.R;
import com.zzq.guli.service.base.result.ResultCodeEnum;
import com.zzq.guli.service.base.util.MD5;
import com.zzq.guli.service.ucenter.entity.LoginForm;
import com.zzq.guli.service.ucenter.entity.Member;
import com.zzq.guli.service.ucenter.entity.RegisterForm;
import com.zzq.guli.service.ucenter.mapper.MemberMapper;
import com.zzq.guli.service.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author ZZQ
 * @since 2024-05-16
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {


    @Autowired
    MemberMapper memberMapper;

    @Override
    public String login(LoginForm loginForm) {

        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("mobile",loginForm.getMobile());
        Member member = memberMapper.selectOne(memberQueryWrapper);
        if(member==null){
          throw new GuliException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }

        //校验密码
        if(!MD5.encrypt(loginForm.getPassword()).equals(member.getPassword())){
            throw new GuliException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //生成jwt
        JwtInfo jwtInfo = new JwtInfo(
                member.getId(),
                member.getNickname(),
                member.getAvatar());

        String token = JwtHelper.createToken(jwtInfo);


        return token;

    }

    @Override
    public void register(RegisterForm registerForm) {
       //验证是否已经注册过
        String mobile=registerForm.getMobile();
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("mobile",mobile);
        Integer integer = memberMapper.selectCount(memberQueryWrapper);
        if(integer>0){
            throw new GuliException(ResultCodeEnum.REGISTER_MOBLE_ERROR);
        }

        Member member = new Member();
        member.setNickname(registerForm.getNickname());
        member.setMobile(registerForm.getMobile());
        member.setDisabled(false);
        String encryptpassword = MD5.encrypt(registerForm.getPassword());
        member.setPassword(encryptpassword);
        memberMapper.insert(member);


    }
}
